package com.example.questionnaires.interceptor;

import com.example.questionnaires.annotation.RequiresAdmin;
import com.example.questionnaires.entity.User;
import com.example.questionnaires.exception.BusinessException;
import com.example.questionnaires.util.UserHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminAuthInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiresAdmin requiresAdmin = handlerMethod.getMethodAnnotation(RequiresAdmin.class);
        if (requiresAdmin == null) {
            return true;
        }
        
        User user = UserHolder.getUser();
        if (user == null || user.getRole() != 1) {
            throw new BusinessException("无权限访问");
        }
        
        return true;
    }
} 